<template>
	<base-popup
		titleT="feed.comment"
		:show="feedStore.commentFeed !== null"
		class="min-h-[80vh]"
		@open="onOpen"
		@close="onClose">
		<div class="flex-1 px-9 py-2 flex flex-col">
			<up-feed-item
				v-if="feedStore.commentFeed !== null"
				:data="feedStore.commentFeed"
				hideFooter></up-feed-item>
			<feed-comment-list class="mt-2" />
		</div>
		<template #footer>
			<div class="px-9 pt-2 pb-5 flex">
				<account-avatar :data="profileStore.userInfo?.avatar" :width="28" />
				<n-input
					ref="textareaRef"
					:autosize="{
						minRows: 1,
						maxRows: 5
					}"
					maxlength="256"
					show-count
					v-model:value="content"
					placeholder=""
					type="textarea"
					size="small"
					class="mx-1 pb-3 flex-1 rounded" />
				<div class="w-[30px]">
					<n-spin v-if="submitLoading" size="small" />
					<base-icon
						v-else
						name="go1"
						class="mt-[5px] text-[30px] text-primary"
						:class="{ 'opacity-50': submitDisabled }"
						@click="submit" />
				</div>
			</div>
		</template>
	</base-popup>
</template>

<script lang="ts" setup>
import { UpFeedItem } from '@/components/up'
import FeedCommentList from './feed-comment-list.vue'
import { NSpin, NInput } from 'naive-ui'
import { ref, computed } from 'vue'
import { BasePopup, BaseIcon } from '@/components/base'
import { AccountAvatar } from '@/components/account'
import { useFeedStore, useProfileStore } from '@/store'
import { addComment } from '@/api/feed'
import { useRequest } from '@/hooks'
import { t } from '@/utils'

defineOptions({ name: 'ViewsFeedComment' })

const feedStore = useFeedStore()
const profileStore = useProfileStore()

const content = ref('')

const textareaRef = ref<any>(null)

const { run: runSubmit, loading: submitLoading } = useRequest(addComment, {
	showSuccess: t('feed.commentSuccess'),
	onSuccess: () => {
		feedStore.commentFeed && feedStore.addComment(feedStore.commentFeed.id)
		onClose()
	}
})

const onOpen = () => {
	textareaRef.value?.focus()
}

const onClose = () => {
	feedStore.showComment(null)
	content.value = ''
}

const submitDisabled = computed(
	() => content.value.trim().length === 0 || content.value.trim().length > 1000
)

const submit = () => {
	if (submitDisabled.value) {
		return
	}
	runSubmit({ tweetId: +feedStore.commentFeed!.id, content: content.value.trim() })
}
</script>
